// 流处理相关工具函数

export class StreamProcessor {
  private decoder = new TextDecoder();
  private buffer = '';

  processChunk(chunk: Uint8Array): string[] {
    this.buffer += this.decoder.decode(chunk, { stream: true });
    const lines = this.buffer.split('\n');
    this.buffer = lines.pop() || '';
    
    return lines.filter(line => line.trim() !== '' && line.trim() !== 'data: [DONE]');
  }

  getRemaining(): string {
    return this.buffer;
  }

  reset() {
    this.buffer = '';
  }
}

export function parseSSEData(line: string): any | null {
  try {
    const jsonStr = line.replace(/^data: /, '');
    return JSON.parse(jsonStr);
  } catch (e) {
    return null;
  }
}

export function formatStreamOutput(content: string, reasoning?: string): void {
  if (reasoning) {
    process.stdout.write(`\n[思考: ${reasoning}]\n`);
  }
  if (content) {
    process.stdout.write(content);
  }
}
